#include<iostream>
#include<unistd.h>
#include<string>
#include"RingQueue.hpp"

struct threaddata
{
    RingQueue<int>* rq;
    std::string name;
};
void* consumer(void* args)//消费者
{
    threaddata* t = static_cast<threaddata*> (args);
    while(true)
    {
        sleep(2);
        int r;
        t -> rq -> Pop(r);
        std::cout << t -> name << "处理了一个任务: " << r << std::endl;
        //break;
    }
    return nullptr;
}

int task = 1;
void* productor(void* args)//生产者
{
    threaddata* t = static_cast<threaddata*> (args);
    while(true)
    {
        t -> rq->Equeue(task);
        std::cout << t -> name << "发送了一个任务: " << task << std::endl;
        task++;
        sleep(1);
        //break;
    }
    return nullptr;
}
int main()
{
    //多线程生产多线程消费的场景
    RingQueue<int>* rq = new RingQueue<int>();//申请一个阻塞队列

    pthread_t p[3],c[2];
    threaddata* rq1 = new threaddata();
    rq1 -> rq = rq;
    rq1 -> name = "生产者1 ";
    pthread_create(p,nullptr,productor,(void*) rq1);

    threaddata* rq2 = new threaddata();
    rq2 -> rq = rq;
    rq2 -> name = "生产者2 ";
    pthread_create(p + 1,nullptr,productor,(void*) rq2);

    threaddata* rq3 = new threaddata();
    rq3 -> rq = rq;
    rq3 -> name = "生产者3 ";
    pthread_create(p + 2,nullptr,productor,(void*) rq3);

    threaddata* rq4 = new threaddata();
    rq4 -> rq = rq;
    rq4 -> name = "消费者1 ";
    pthread_create(c,nullptr,consumer,(void*) rq4);

    threaddata* rq5 = new threaddata();
    rq5 -> rq = rq;
    rq5 -> name = "消费者2 ";
    pthread_create(c + 1,nullptr,consumer,(void*) rq5);



    pthread_join(p[0],nullptr);
    pthread_join(p[1],nullptr);
    pthread_join(p[2],nullptr);
    pthread_join(c[0],nullptr);
    pthread_join(c[1],nullptr);

    delete rq;
    delete rq1;
    delete rq2;
    delete rq3;
    delete rq4;
    delete rq5;

    return 0;
}